<?php
declare (strict_types = 1);

namespace app\auth\model;

use think\Model;

/**
 * @mixin think\Model
 */
class Member extends Model
{
    // 设置json类型字段
    protected $json = ['wx_info','wx_tags'];
    // 设置JSON数据返回数组
    protected $jsonAssoc = true;
    // 定义时间戳字段名
    protected $createTime = 'reg_time';
    protected $updateTime = 'update_time';
    // public function getWxTagsAttr($value, $data){
    //     return $value === null ? [] : explode(',',$value);
    // }
    public function getPasswordAttr($value)
    {
        return '';
    }
    public function getSaltAttr($value)
    {
        return '';
    }
    // 保存管理员最后登陆时间
    public function setLastloginTime($username)
    {
        return $this->where('username',$username)->setField('lastlogin_time',time());
    }
    public function getLastloginTimeAttr($value)
    {
        return  empty($value)?'未登录':date('Y-m-d H:i:s', $value);
    }
    // 用户头像
    public function getAvatarAttr($value,$data){
        // return !empty($value) ? $value: 'https://cdn.vuetifyjs.com/images/parallax/material.jpg';
    }

    public function saveSubscribeInfo($wx_info){
        $openid = $wx_info['openid'];
        $user = $this->where('wx_openid',$openid)->find();
        if($user){
            if($wx_info['subscribe'] == 1) {
            $this->where('wx_openid',$openid)->save([
                'wx_nickname'=>$wx_info['nickname'],
                'wx_openid'=>$openid,
                'wx_info'=>$wx_info,
                'wx_subscribe'=>$wx_info['subscribe'],
                'wx_tags'=>$wx_info['tagid_list']
            ]);
            } else {
                $this->where('wx_openid',$openid)->save(['wx_subscribe'=>$wx_info['subscribe']]);
            }
        } else {
            $this->save([
                'wx_nickname'=>$wx_info['nickname'],
                'wx_openid'=>$openid,
                'wx_info'=>$wx_info,
                'wx_subscribe'=>$wx_info['subscribe'],
                'wx_tags'=>$wx_info['tagid_list']
            ]);
        }
    }
    // 使用用户登录信息更新wx_info字段
    public function updateFormWx($wx_info){
        $openid = $wx_info['openid'];
        $user = $this->where('wx_openid',$openid)->find();
        if($user){
            $info = array_merge($user->wx_info,$wx_info);
            $this->where('wx_openid',$openid)->save(['wx_info'=>$info,'wx_nickname'=>$info['nickname']]);
            return $user->id;
        } else {
            // 未关注
            return null;
        }
    }
}
